﻿using DG.Tweening;
using UnityEngine;
using XLua;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Yoozoo.UI.YGUI;

namespace Yoozoo.Gameplay.RTS
{
    public class NewYearHudLod0 : MonoBehaviour
    {
        public YButton clickButton;
        public YImage progressImage;
        public YImage iconImage;

        private LuaFunction m_clickCallback;
        private float m_clickCDTime;

        private Tween m_progressTween;

        private ResLoader _resLoader;

        private bool m_playingEffect = false;

        void Awake()
        {
            progressImage.fillAmount = 0;
            clickButton.onClick.AddListener(() =>
            {
                if (m_playingEffect)
                {
                    return;
                }

                m_playingEffect = true;
                m_progressTween = progressImage.DOFillAmount(1, m_clickCDTime).SetEase(Ease.Linear);
                m_progressTween.onComplete = OnComplete;
            });
        }

        private void OnComplete()
        {
            KillTweenObj();
            m_clickCallback?.Action();
            progressImage.fillAmount = 0;
            m_playingEffect = false;
        }

        void OnDestroy()
        {
            KillTweenObj();
            if (_resLoader!=null)
            {
                _resLoader.Recycle2Cache();
                _resLoader = null;
            }
        }

        private void KillTweenObj()
        {
            if (m_progressTween != null)
            {
                m_progressTween.Kill();
                m_progressTween = null;
            }
        }

        public void SetClickCallback(LuaFunction callback)
        {
            m_clickCallback = callback;
        }

        public void SetClickCDTime(float clickCDTime)
        {
            m_clickCDTime = clickCDTime;
        }

        public void SetIconImagePath(string imagePath)
        {
            if (_resLoader == null)
            {
                _resLoader = ResLoader.Alloc();
            }
            _resLoader.Add2Load(imagePath, typeof(Sprite), (success, assetName, asset) =>
            {
                if (!success)
                {
                    return;
                }
            
                if (assetName != imagePath)
                {
                    return;
                }
                
                iconImage.sprite = asset as Sprite;
            });
            _resLoader.Load();
        }
    }
}
